package com.seecen.controller;

import com.seecen.pojo.dto.PetDTO;
import com.seecen.pojo.entity.Pet;
import com.seecen.service.PetService;
import com.seecen.utils.FileUploadUtil;
import com.seecen.utils.JwtHelper;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/pet")
@CrossOrigin
public class PetController {

    @Autowired
    private PetService petService;

    @Autowired
    private FileUploadUtil fileUploadUtil;
    
    @Autowired
    private JwtHelper jwtHelper;

    @PostMapping("/add")
    public Result addPet(PetDTO petDTO, 
                         @RequestParam(value = "image", required = false) MultipartFile image, 
                         HttpServletRequest request) {
        // 检查用户是否登录
        String token = request.getHeader("token");
        if (token == null || jwtHelper.isExpiration(token)) {
            return Result.build(null, ResultCode.NOTLOGIN);
        }
        
        try {
            // 如果有上传图片，则处理图片上传
            if (image != null && !image.isEmpty()) {
                String imageUrl = fileUploadUtil.uploadImage(image);
                petDTO.setPetImage(imageUrl);
            }

            // 添加宠物信息
            Pet pet = petService.addPet(petDTO);

            return Result.ok(pet);
        } catch (IllegalArgumentException e) {
            log.error("添加宠物参数错误", e);
            return Result.build(null, ResultCode.PET_NAME_EXISTS);
        } catch (Exception e) {
            log.error("添加宠物失败", e);
            return Result.build(null, ResultCode.PET_ADD_FAILED);
        }
    }
}